 #!/usr/bin/env python

# -*- coding: utf-8 -*-
# @Time : 2023/12/22 16:38
# @Author : Nabby
# @FileName: responser.py.py

import json
from datetime import datetime
from typing import Tuple, Union
from flask import g, jsonify
import traceback
from flask import Request
from infrastructure.utils.common.logger import log_task_main

CODE = {
    # 正常操作
    10000: "操作成功",
    # 逻辑异常
    10001: "账号不存在",
    10002: "密码错误",
    10003: "更新用户失败，用户名已存在！",
    10004: "新建用户失败，用户名已存在！",
    10005: "旧密码错误",
    10006: "新建角色失败，角色名已存在！",
    10007: "更新角色失败，角色名已存在！",
    10008: "角色不存在！",
    10009: "删除用户失败，用户不存在！",
    10022: "该记录不存在",
    10023: "请先下架再编辑",
    10024: "企业用户不存在",
    10032: "该诉求状态无法确认完成",
    10033: "此条目有关联数据，请解绑后再尝试",
    10034: "企业不存在",

    10041: "订单已存在，无法保存！",
    10042: "预报信息已存在，无法保存！",
    10043: "收货信息已存在，无法保存！",
    10044: "预报信息不存在！",
    10045: "收货信息不存在！",
    10046: "申报信息已存在，无法保存！",
    10047: "装箱单信息已存在，无法保存！",
    10048: "申报信息不存在！",
    10049: "装箱单信息不存在！",
    10050: "费用信息不存在！",
    10051: "物流轨迹不存在！",
    10052: "订单不存在！",
    10053: "请先删除关联的装箱单信息后重试！",
    10054: "文件不存在！",


    10064: "字典类型已存在！",
    10065: "值已存在，无法保存！",
    10066: "无权限！",

    # 字典管理
    10086: "修改失败，序号已被占用",
    10087: "字典模块操作仅支持超级管理员编辑,请知悉",
    20001: "超时登出",
    20003: "JSON格式异常",
    # 非法行为
    30001: "操作非法",
    30005: "填入数据非法",
    # 系统异常
    40001: "系统异常",
    40002: "mysql服务异常",
    46005: "错误代码46005",
    46006: "文件上传失败",
    # 接口服务
    50002: "参数名错误",
    51000: "接口异常",
}


def data_converter(data):
    """Json转换特定格式的值

    Args:
        data (str): 不能被 json.jumps 进行序列化的数据

    Returns:
        str: 转换后的数据
    """
    if isinstance(data, datetime):
        return data.strftime("%Y-%m-%d %H:%M:%S")


def send(
    code: int = 10000,
    data: Union[str, list, dict] = "",
    msg: str = "操作成功",
    is_replace=False,
) -> str:
    """返回数据封装

    Args:
        code (int): 响应消息编码
        data (Union[str, list], optional): 请求响应的内容. Defaults to "".
        msg (str, optional): 请求响应的消息. Defaults to "".
        is_replace (bool, optional):

    Returns:
        str: 请求响应消息的完整 Json 格式字符串
    """
    if code in CODE.keys():
        return jsonify({"code": code, "msg": CODE[code], "data": data})
    else:
        return jsonify({"code": code, "msg": msg, "data": data})
    # if code in {10000, 10079, 50002}:
    #     return json.dumps(
    #         {"code": code, "msg": msg if is_replace else CODE[code], "data": data},
    #         default=data_converter,
    #     )
    # if is_replace:
    #     return json.dumps({"code": code, "msg": msg}, default=data_converter)
    # else:
    #     return json.dumps({"code": code, "msg": CODE[code]}, default=data_converter)


# 校验post_json 数据格式是否符合参数列表 若不符合，提示差集
def post_param_check(request, param_list):
    try:
        rjson = request.json
        # rjson = request.get_json()
        rkeys_list = list(rjson.keys())
        has_list = list(set(rkeys_list).intersection(set(param_list)))
        no_match_list = list(set(has_list) ^ set(param_list))
        return (
            ("error", send(50002, no_match_list))
            if no_match_list
            else ("success", rjson)
        )
    except Exception as e:
        sign = "=" * 60 + "\n"
        msg = f"{sign}>>>异常接口：\t{request.url}\n>>>异常信息：\t{e}"
        msg_traceback = f"{sign}{traceback.format_exc()}{sign}"
        log_task_main(f"\n{msg}\n{msg_traceback}", level="error")
        return "error", send(20003)
